/*
 * Copyright (c) 2017 Hazuki
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.hazuki.yuzubrowser.backup;

import android.content.Context;
import android.content.SharedPreferences;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;

public class PrefXmlParser {

    private SharedPreferences pref;

    public PrefXmlParser(Context context, String name) {
        pref = context.getSharedPreferences(name, Context.MODE_PRIVATE);
    }

    public void load(InputStream inputStream) throws XmlPullParserException, IOException {
        XmlPullParser parser = createParser();
        parser.setInput(inputStream, "UTF-8");

        SharedPreferences.Editor e = pref.edit();

        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                startTag(e, parser.getName().toLowerCase(), parser);
            }
            eventType = parser.next();
        }
        e.apply();
    }

    private void startTag(SharedPreferences.Editor e, String tag, XmlPullParser parser) throws IOException, XmlPullParserException {
        switch (tag) {
            case "int":
                e.putInt(parser.getAttributeValue(null, "name"), Integer.valueOf(parser.getAttributeValue(null, "value")));
                break;
            case "long":
                e.putLong(parser.getAttributeValue(null, "name"), Long.valueOf(parser.getAttributeValue(null, "value")));
                break;
            case "float":
                e.putFloat(parser.getAttributeValue(null, "name"), Float.valueOf(parser.getAttributeValue(null, "value")));
                break;
            case "boolean":
                e.putBoolean(parser.getAttributeValue(null, "name"), Boolean.valueOf(parser.getAttributeValue(null, "value")));
                break;
            case "string":
                e.putString(parser.getAttributeValue(null, "name"), parser.nextText());
                break;
        }
    }

    private XmlPullParser createParser() throws XmlPullParserException {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        return factory.newPullParser();
    }

}
